package by.koleda.photoupdater;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import by.koleda.photoupdater.fragment.LoginDialogFragment;
import by.koleda.photoupdater.fragment.SyncDialogFragment;
import by.koleda.photoupdater.helpers.VkOAuthHelper;
import by.koleda.photoupdater.service.HttpService;
import by.koleda.photoupdater.service.MakeSuggestionsService;

public class MainActivity extends FragmentActivity {
	
	private static final String LOGIN_DIALOG_TAG = "login_dialog_tag";
	private static final String SYNC_DIALOG_TAG = "sync_dialog_tag";
	
	private static final String TAG = MainActivity.class.getSimpleName();
	
	private BroadcastReceiver mHttpServiceReceiver;
	private BroadcastReceiver mSuggestionsReceiver;
	
	private ProgressDialog mDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void onStartSyncClick(View view) {
		if (!VkOAuthHelper.isLogged(getApplicationContext())) {
			proceedLogin();
		} else {
			showProgressDialog(R.string.loading_title, R.string.contacts_receive, false);
			startSyncService();
			
			mHttpServiceReceiver = new BroadcastReceiver() {
	
				@Override
				public void onReceive(Context context, Intent intent) {
					String action = intent.getAction();
					if (action.equals(HttpService.ACTION_ON_SUCCESS)) {
						hideProgressDialog();
						unregisterReceiver(mHttpServiceReceiver);
						stopService(intent);
						startSuggestionsService();
					} else if (action.equals(HttpService.ACTION_ON_ERROR)) {
						hideProgressDialog();
						stopService(intent);
						Toast.makeText(MainActivity.this, R.string.contacts_failure, Toast.LENGTH_LONG).show();
						Log.w(TAG, intent.getStringExtra(HttpService.EXTRA_KEY_MESSAGE));
					}
				}
			};
			IntentFilter filter = new IntentFilter();
			filter.addAction(HttpService.ACTION_ON_SUCCESS);
			filter.addAction(HttpService.ACTION_ON_ERROR);
			registerReceiver(mHttpServiceReceiver, filter);
		}
	}
	
	public void onContactsClick(View view) {
		Intent intent = new Intent(MainActivity.this, ContactsActivity.class);
		startActivity(intent);
	}

	private void startSyncService() {
		Intent intent = new Intent(this, HttpService.class);
		startService(intent);
	}
	
	private void startSuggestionsService() {
		showProgressDialog(R.string.loading_title, R.string.contacts_suggest, false);
		mSuggestionsReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(MakeSuggestionsService.ACTION_ON_SUCCESS)) {
					hideProgressDialog();
					unregisterReceiver(mSuggestionsReceiver);
					stopService(intent);
					showSyncOptions();
				} else if (action.equals(MakeSuggestionsService.ACTION_ON_ERROR)) {
					hideProgressDialog();
					unregisterReceiver(mSuggestionsReceiver);
					stopService(intent);
					Toast.makeText(MainActivity.this, intent.getStringExtra(MakeSuggestionsService.EXTRA_KEY_MESSAGE), Toast.LENGTH_SHORT).show();
				}
			}
			
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(MakeSuggestionsService.ACTION_ON_SUCCESS);
		filter.addAction(MakeSuggestionsService.ACTION_ON_ERROR);
		registerReceiver(mSuggestionsReceiver, filter);
		Intent intent = new Intent(this, MakeSuggestionsService.class);
		startService(intent);
	}

	private void proceedLogin() {
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        LoginDialogFragment dialogFragment = new LoginDialogFragment();
    	transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    	transaction.add(dialogFragment, LOGIN_DIALOG_TAG);
    	transaction.commit();
	}
	
	private void showSyncOptions() {
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        SyncDialogFragment dialogFragment = new SyncDialogFragment();
    	transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    	transaction.add(dialogFragment, SYNC_DIALOG_TAG);
    	transaction.commit();
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("MainActivity", "onActivityResult called");
		if ((requestCode == 1 || requestCode == 2) || (requestCode == 0)) {
			if (resultCode == RESULT_OK) {
				int result = data.getIntExtra(SuggestionsActivity.SUBMIT_TAG, 0);
				
				if (result != -1) {
					Toast.makeText(this, R.string.suggestions_success, Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(this, R.string.suggestions_failure, Toast.LENGTH_LONG).show();
				}
			}
		}
		
		if (requestCode == 5) {
			if (resultCode == RESULT_OK) {
				onStartSyncClick(findViewById(R.id.button_main_start));
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_vk_logoff:
				VkOAuthHelper.exit(getApplicationContext());
				Toast.makeText(MainActivity.this, R.string.logoff_success, Toast.LENGTH_LONG).show();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	public void showProgressDialog(int title, int msg, boolean horizontal) {
		CharSequence message = getText(msg);
		mDialog = new ProgressDialog(this);
		mDialog.setTitle(title);
		mDialog.setMessage(message);
		mDialog.setIndeterminate(true);
	    mDialog.setCancelable(false);
	    if (horizontal) {
	    	mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    }
	    mDialog.show();
	}
	
	public void hideProgressDialog() {
		mDialog.dismiss();
	}
	
}
